<template>
    <div class="app-container" style="padding: 0" ref="divDom">
        <vxe-grid ref="xGrid" v-bind="gridOptions" :height="tableHeight" @checkbox-change="handleSelectionChange" @cell-click="rowClick" @form-submit="search" @form-reset="reset">
            <template #toolbar_buttons>
                <el-row :gutter="10">
                    <el-col :span="1.5">
                        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['system:dict:add']">新增</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete" v-hasPermi="['system:dict:remove']">删除</el-button>
                    </el-col>
                    <el-col :span="1.5">
                        <el-button type="danger" plain icon="Refresh" @click="handleRefreshCache" v-hasPermi="['system:dict:remove']">刷新缓存</el-button>
                    </el-col>
                </el-row>
            </template>
            <template #slotStatus="{ row }">
                <dict-tag :options="sys_normal_disable" :value="row.status" />
            </template>
            <template #action="{ row }">
                <el-button link type="primary" icon="Edit" @click="handleUpdate(row)" v-hasPermi="['system:dict:edit']">修改</el-button>
                <el-button link type="primary" icon="Delete" @click="handleDelete(row)" v-hasPermi="['system:dict:remove']">删除</el-button>
            </template>
        </vxe-grid>
        <dictionary-edit :dialog-visible="dialog.isVisible" :type="dialog.type" :dictType="dictType" @close="editClose" @success="editSuccess" ref="edit" />
    </div>
</template>

<script setup lang="ts" name="DictTypeManage">
    import dictionaryEdit from "./edit";
    import { reactive, getCurrentInstance, ref, onMounted, onBeforeUnmount } from "vue";
    import useDictStore from "@/store/modules/dict";
    import { pageType, getType, delType, refreshCache } from "@/api/system/dict/type";
    import { VxeGridInstance, VxeGridProps } from "../../../../types/index";
    import XEUtils from "xe-utils";
    import { VXETable } from "../../../../packages/all";
    import { getViewportOffset } from "@/utils/domUtils";
    import { removeObjectNull } from "@/utils";
    const edit = ref<InstanceType<typeof dictionaryEdit>>();
    const { proxy } = getCurrentInstance() as any;
    const { sys_normal_disable } = proxy.useDict("sys_normal_disable");
    const ids = ref<any[]>([]);
    const single = ref(true);
    const multiple = ref(true);
    const emit = defineEmits(["dictionaryClick", "resetItem"]);
    const dictType = ref();
    const dialog = ref({
        isVisible: false,
        type: "add",
    });
    const xGrid = ref({} as VxeGridInstance);

    const divDom = ref() as Ref<HTMLDivElement>;
    const tableHeight = ref("100%");
    function calcHeight() {
        const viewport = getViewportOffset(divDom.value);
        tableHeight.value = viewport.bottomIncludeBody - 30;
    }
    onMounted(() => {
        calcHeight();
        window.addEventListener("resize", calcHeight);
    });
    onBeforeUnmount(() => {
        window.removeEventListener("resize", calcHeight);
    });
    const gridOptions = reactive<VxeGridProps>({
        border: true,
        resizable: true,
        showHeaderOverflow: true,
        showOverflow: true,
        highlightHoverRow: true,
        keepSource: true,
        id: "6",
        height: tableHeight.value,
        rowId: "dictId",
        sortConfig: {
            trigger: "cell",
            remote: true,
        },
        filterConfig: {
            remote: true,
        },
        pagerConfig: {
            pageSize: 10,
            pageSizes: [5, 10, 15, 20, 50, 100, 200, 500, 1000],
            perfect: true,
        },
        formConfig: {
            titleWidth: 100,
            titleAlign: "right",
            items: [
                {
                    field: "dictName",
                    title: "字典名称",
                    span: 12,
                    itemRender: { name: "$input", props: { placeholder: "请输入字典名称" } },
                },
                {
                    field: "dictType",
                    title: "字典类型",
                    span: 12,
                    itemRender: { name: "$input", props: { placeholder: "请输入字典类型" } },
                },
                {
                    field: "status",
                    title: "状态",
                    span: 6,
                    itemRender: {
                        name: "$select",
                        options: sys_normal_disable,
                    },
                    titleWidth: 50,
                },
                {
                    field: "createTime",
                    title: "创建时间",
                    span: 12,
                    itemRender: {
                        name: "ElDatePicker",
                        props: {
                            valueFormat: "YYYY-MM-DD",
                            type: "daterange",
                            rangeSeparator: "-",
                            startPlaceholder: "开始日期",
                            endPlaceholder: "结束日期",
                        },
                    },
                },
                {
                    itemRender: {
                        name: "$buttons",
                        children: [
                            {
                                props: {
                                    type: "submit",
                                    content: "查询",
                                    status: "primary",
                                },
                            },
                            {
                                props: {
                                    type: "reset",
                                    content: "重置",
                                },
                            },
                        ],
                    },
                },
            ],
        },
        toolbarConfig: {
            refresh: true,
            zoom: true,
            custom: true,
            export: proxy.$auth.hasPermi("system:dict:export"),
            slots: {
                buttons: "toolbar_buttons",
            },
        },
        proxyConfig: {
            paramsChangeLoad: false, //额外的请求参数改变时是否重新请求数据
            seq: true, // 启用动态序号代理，每一页的序号会根据当前页数变化
            sort: true, // 启用排序代理，当点击排序时会自动触发 query 行为
            filter: true, // 启用筛选代理，当点击筛选时会自动触发 query 行为
            form: true, // 启用表单代理，当点击表单提交按钮时会自动触发 reload 行为
            // 对应响应结果 { result: [], page: { total: 100 } }
            props: {
                result: "rows", // 配置响应结果列表字段
                total: "total", // 配置响应结果总页数字段
            },
            ajax: {
                // 接收 Promise
                query: ({ page, sorts, filters, form, params }: any) => {
                    // 处理时间范围查询
                    const createTime = proxy.addDateRange({}, form.createTime, "createTime");
                    const queryParams: any = Object.assign({}, form, createTime, page, params);
                    // 处理排序条件
                    const orderByColumn = <Array<String>>[];
                    const isAsc = <Array<Boolean>>[];
                    sorts.forEach((m: any) => {
                        orderByColumn.push(m.field);
                        isAsc.push(m.order);
                    });
                    queryParams.orderByColumn = orderByColumn.join(",");
                    queryParams.isAsc = isAsc.join(",");
                    // 处理筛选条件
                    filters.forEach(({ property, values }: any) => {
                        queryParams[property] = values.join(",");
                    });
                    return pageType({
                        ...removeObjectNull(queryParams),
                    }).then((response) => {
                        return response;
                    });
                },
            },
        },
        checkboxConfig: {
            trigger: "row",
        },
        columns: [
            { type: "checkbox", width: 60 },
            {
                field: "dictId",
                title: "字典编号",
                sortable: true,
            },
            {
                field: "dictName",
                title: "字典名称",
                sortable: true,
            },
            {
                field: "dictType",
                title: "字典类型",
            },
            {
                field: "status",
                title: "状态",
                filters: sys_normal_disable,
                slots: {
                    default: "slotStatus",
                },
            },
            {
                field: "remark",
                title: "备注",
                sortable: true,
            },
            {
                field: "createTime",
                title: "创建时间",
                visible: false,
                sortable: true,
                formatter({ cellValue }: any) {
                    return XEUtils.toDateString(cellValue, "yyyy-MM-dd HH:ss:mm");
                },
            },

            {
                title: "操作",
                width: 150,
                align: "center",
                fixed: "right",
                slots: { default: "action" },
            },
        ],
    });

    /** 新增按钮操作 */
    function handleAdd() {
        dialog.value.isVisible = true;
        dialog.value.type = "add";
    }
    /** 多选框选中数据 */
    function handleSelectionChange(selection: any) {
        ids.value = selection.records.map((item: any) => item.dictId);
        single.value = selection.records.length != 1;
        multiple.value = !selection.records.length;
    }
    /** 修改按钮操作 */
    function handleUpdate(row: any) {
        const dictId = row.dictId || ids.value;
        getType(dictId).then((response) => {
            dictType.value = response.data;
            dialog.value.isVisible = true;
            dialog.value.type = "edit";
        });
    }
    /** 删除按钮操作 */
    function handleDelete(row: any) {
        const dictIds = row.dictId || ids.value;
        proxy.$modal
            .confirm('是否确认删除字典编号为"' + dictIds + '"的数据项？')
            .then(function () {
                return delType(dictIds);
            })
            .then(() => {
                xGrid.value.commitProxy("reload");
                proxy.$modal.msgSuccess("删除成功");
            })
            .catch(() => {});
    }
    /** 刷新缓存按钮操作 */
    function handleRefreshCache() {
        refreshCache().then(() => {
            proxy.$modal.msgSuccess("刷新成功");
            useDictStore().cleanDict();
        });
    }
    //点击行
    function rowClick({ row }: any) {
        emit("dictionaryClick", row);
    }
    // 弹窗关闭
    function editClose() {
        dialog.value.isVisible = false;
    }
    //弹窗操作成功
    function editSuccess() {
        xGrid.value.commitProxy("reload");
        dialog.value.isVisible = false;
    }
    //查询事件
    function search() {
        emit("resetItem");
    }
    //重置查询
    function reset() {
        emit("resetItem");
    }
</script>
<style lang="scss" scoped></style>
